﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Configuration;

namespace lzsoft.CDN
{
    public class ProxyHandler : IHttpHandler
    {
        static string[] parts;

        static ProxyHandler()
        {
            parts = ConfigurationManager.AppSettings["SOURCE_SITE"].Split(':');
        }

        public bool IsReusable
        {
            get { return false; }
        }

        public void ProcessRequest(HttpContext context)
        {
            string imgPath = ToLocalPath(context.Request.Url);
            if (!File.Exists(imgPath))
            {
                try
                {
                    HttpSocket socket = new HttpSocket(context.Request.Url.AbsolutePath, parts[1], parts[0], imgPath);
                    socket.SaveStream();
                }
                catch(Exception ex)
                {
                    context.Response.Write(ex.StackTrace);
                    context.Response.Write(ex.Message);
                }
            }

            if (File.Exists(imgPath))
            {
                context.Response.WriteFile(imgPath);
                //context.Response.TransmitFile(imgPath);
                context.Response.ContentType = "image/jpeg";
                context.Response.End();
            }
            else
            {
                context.Response.Write("server error!");
                context.Response.End();
            }
        }

        public string ToLocalPath(Uri url)
        {
            string root = HttpContext.Current.Server.MapPath("~");
            if (url.AbsolutePath.StartsWith(@"/"))
            {
                return Path.Combine(new string[] { root, url.AbsolutePath.Substring(1) });
            }
            return Path.Combine(new string[] { root, url.AbsolutePath });
        }
    }
}